package com.tp.controller.system;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.tp.base.BaseController;
import com.tp.model.sys.SysMenu;
import com.tp.service.MenuService;
import java.util.List;

/**
 * 菜单管理
 * 
 * @author TP
 *
 */
@ControllerBind(controllerKey = "/system/menu")
public class MenuController extends BaseController {

	private static final String path = "/pages/system/menu/menu_";

	@Inject
	MenuService service;

	public void index() {
		render(path + "list.html");
	}

	public void list() {
		SysMenu model = getModelByAttr(SysMenu.class);
		// 排序
		String orderBy = getBaseForm().getOrderBy();
		Page<SysMenu> page = service.getPageByWhere(model, orderBy, getPaginator());
		renderCount(page.getTotalRow(), page.getList());
	}

	public void form() {
		int id = getParaToInt("id", 0);
		if (id == 0) {
			SysMenu model = new SysMenu();
			model.setStatus(1);
			setAttr("model", model);
			setAttr("parentSelect", service.selectMenu(0));
		} else {
			SysMenu model = new SysMenu().dao().findById(id);
			setAttr("model", model);
			setAttr("parentSelect", service.selectMenu(model.getParentId()));
		}
		render(path + "form.html");
	}

	@Before(Tx.class)
	public void delete() {
		Integer uid = getUID();
		String[] ids = getPara("ids").split(",");
		boolean flag = service.deleteObject(ids, uid);
		if (flag) {
			setSessionUser(getSessionUser());
			renderOk("删除成功");
		} else {
			renderFail("删除失败");
		}
	}

	public void save() {
		SysMenu model = getModel(SysMenu.class);
		// 根目录级别为1
		Integer parentid = model.getInt("parent_id");
		if (parentid != null) {
			model.set("level", parentid == 0 ? 1 : 2);
		}
		// 修改保存前对名称做唯一验证
		List<SysMenu> sysMenus = model.findByWhere("where name = ?", model.getStr("name"));
		// 日志添加
		Integer userid = getUID();
		String now = getNow();
		boolean flag = false;
		if (model.getInt("id") != null && model.getInt("id") > 0) { // 更新
			sysMenus = model.findByWhere("where name = ? and id != ?", model.get("name"), model.get("id"));
			if (sysMenus != null && sysMenus.size() > 0) {
				renderFail("保存失败,菜单名称重复");
				return;
			} else {
				model.put("update_id", userid);
				model.put("update_time", now);
				flag = model.update();
			}
		} else { // 新增
			if (sysMenus != null && sysMenus.size() > 0) {
				renderFail("保存失败,菜单名称重复");
				return;
			} else {
				model.remove("id");
				model.put("create_id", userid);
				model.put("create_time", now);
				flag = model.save();
			}
		}
		if (flag) {
			renderOk("保存成功");
		} else {
			renderFail("保存失败");
		}
	}
}